
#自定义模型管理器
from django import forms
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm

from zlauth.models import CaptchaModel

User = get_user_model()

#给form表单添加校验
class RegistrationForm(forms.Form):
     #给指定的字段添加校验 和  vue中一样
     username = forms.CharField(max_length=30,min_length=3,required=True,error_messages={
         'required': '请传入用户名',
         "max_length": "用户名长度在2-20之间!",
         "min_length": "用户名长度在2-20之间!",
     })
     email = forms.EmailField(max_length=100,required=True,error_messages={
         'required': '请传入邮箱',
         'invalid': '请传入一个正确的邮箱！'
     })
     captcha=forms.CharField(max_length=4,min_length=4,required=True)
     password=forms.CharField(max_length=20,min_length=6,required=True)

     #需要验证邮箱是否已经注册
     def clean_email(self):
         email=self.cleaned_data['email']
         if User.objects.filter(email=email).exists():
             #抛出异常
             raise  forms.ValidationError('邮箱已经被注册')
         return email

     def clean_captcha(self):
         captcha=self.cleaned_data['captcha']
         email=self.cleaned_data['email']
         #校验验证码
         captcha_model=CaptchaModel.objects.filter(email=email,captcha=captcha)[0]
         if captcha_model is None:
             raise forms.ValidationError('验证码错误')
         #验证完用完之后删除
         captcha_model.delete()
         return captcha

class LoginForm(forms.Form):
   email = forms.EmailField(required=True,error_messages={
       'required': '请传入邮箱',
       'invalid': '请传入一个正确的邮箱！'
   })
   password = forms.CharField(min_length=6,max_length=20,required=True,error_messages={
       'required': '请传入密码',
   })
   remember_me= forms.IntegerField(required=False)